<script setup lang="ts">
import type { Recordable } from '@vben/types';

import { computed, ref } from 'vue';

import { Page, useVbenDrawer, type VbenFormProps } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space, Tabs, TabPane } from 'ant-design-vue';

import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  type VxeGridProps,
} from '#/adapter/vxe-table';

import {
  manageApprove,
  manageExport,
  manageList,
  manageRemove,
} from '#/api/patient/manage';
import type { ManageForm } from '#/api/patient/manage/model';
import { commonDownloadExcel } from '#/utils/file/download';

import manageDrawer from './manage-drawer.vue';
import { columns, querySchema } from './data';
import { router } from '#/router';

const activeTab = ref('0');

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await manageList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          status: activeTab.value === 'all' ? undefined : activeTab.value,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'userId',
  },
  id: 'patient-manage-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [ManageDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: manageDrawer,
});

function handleTabChange() {
  const status = activeTab.value;
  let cols = columns;
  if (status === '0' || status === '4') {
    cols = columns!.filter((col) => col.field !== 'enrollmentDate');
  }
  tableApi.grid.reloadColumn(cols); // 关键：动态刷新列
  tableApi.query();
}

async function handleApprove() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<ManageForm>) => row.id);
  await manageApprove(ids);
  await tableApi.query();
}

async function handleEdit(row: Required<ManageForm>) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

async function handleInfo(row: Required<ManageForm>) {
  router.push(`/patient/detail/${row.id}/${row.patientName}`);
}

async function handleDelete(row: Required<ManageForm>) {
  await manageRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<ManageForm>) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await manageRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  commonDownloadExcel(
    manageExport,
    '患者用户数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}

// /**
//  * 只有超级管理员才能修改
//  */
// const { hasAccessByCodes, hasAccessByRoles } = useAccess();

// const isSuperAdmin = computed(() => {
//   return hasAccessByRoles(['superadmin']);
// });
</script>

<template>
  <Page :auto-content-height="true">
    <Tabs
      v-model:active-key="activeTab"
      @change="handleTabChange"
      class="h-[60px]"
    >
      <TabPane key="0" tab="待审核" />
      <TabPane key="1" tab="在组中" />
      <TabPane key="2" tab="已完成" />
      <TabPane key="3" tab="已退出" />
      <TabPane key="4" tab="已拒绝" />
      <TabPane key="all" tab="全部" />
    </Tabs>
    <div style="height: calc(100% - 60px)">
      <BasicTable table-title="患者用户列表">
        <template #toolbar-tools>
          <Space>
            <a-button
              v-access:code="['business:enrollment:export']"
              @click="handleDownloadExcel"
            >
              {{ $t('pages.common.export') }}
            </a-button>
            <a-button
              :disabled="!vxeCheckboxChecked(tableApi)"
              danger
              type="primary"
              v-access:code="['business:enrollment:remove']"
              @click="handleMultiDelete"
            >
              {{ $t('pages.common.delete') }}
            </a-button>
            <a-button
              :disabled="!vxeCheckboxChecked(tableApi)"
              type="primary"
              v-access:code="['business:enrollment:approve']"
              @click="handleApprove"
            >
              {{ '批量入组' }}
            </a-button>
          </Space>
        </template>
        <template #action="{ row }">
          <Space>
            <ghost-button
              v-access:code="['business:enrollment:edit']"
              @click.stop="handleInfo(row)"
            >
              {{ $t('pages.common.info') }}
            </ghost-button>
            <ghost-button
              v-access:code="['business:enrollment:edit']"
              @click.stop="handleEdit(row)"
            >
              {{ $t('pages.common.edit') }}
            </ghost-button>
            <Popconfirm
              :get-popup-container="getVxePopupContainer"
              placement="left"
              title="确认删除？"
              @confirm="handleDelete(row)"
            >
              <ghost-button
                danger
                v-access:code="['business:enrollment:remove']"
                @click.stop=""
              >
                {{ $t('pages.common.delete') }}
              </ghost-button>
            </Popconfirm>
          </Space>
        </template>
      </BasicTable>
    </div>

    <ManageDrawer @reload="tableApi.query()" />
  </Page>
</template>
